package com.logos.cartoon.ui;

import com.formdev.flatlaf.FlatDarkLaf;
import com.logos.cartoon.service.UserService;
import net.miginfocom.swing.MigLayout;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author rose
 * @date 2025/05/23
 */
@Component
public class RegisterFrame extends JFrame {

    private UserService userService;

    public RegisterFrame() {
        setTitle("注册");
        setSize(800, 600);
        // 居中显示
        setLocationRelativeTo(null);

        // 使用 MigLayout 进行布局
        // 正确使用方式示例：
        JPanel panel = new JPanel(new MigLayout("fill", "[][]", "[][][]"));

        // 用户名标签和输入框
        JLabel userLabel = new JLabel("用户名:");
        JTextField userText = new JTextField(20);

        panel.add(userLabel, "gapright 10");
        panel.add(userText, "wrap");

        // 密码标签和输入框
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField(20);

        panel.add(passwordLabel, "gapright 10");
        panel.add(passwordField, "wrap");

        // 确认密码标签和输入框
        JLabel confirmPasswordLabel = new JLabel("确认密码:");
        JPasswordField confirmPasswordField = new JPasswordField(20);

        panel.add(confirmPasswordLabel, "gapright 10");
        panel.add(confirmPasswordField, "wrap");

        // 注册按钮
        JButton registerButton = new JButton("注册");

        panel.add(registerButton, "center");

        // 添加按钮点击事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = userText.getText();
                String password = new String(passwordField.getPassword());

                if (userService.register(username, password)) {
                    JOptionPane.showMessageDialog(RegisterFrame.this, "登录成功！");
                    dispose(); // 关闭注册窗口
                } else {
                    JOptionPane.showMessageDialog(RegisterFrame.this, "用户名或密码错误！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 设置 FlatLaf 主题
        try {
            UIManager.setLookAndFeel(new FlatDarkLaf());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        SwingUtilities.updateComponentTreeUI(this);

        // 将面板添加到窗口
        add(panel);

        setVisible(true);
    }
}
